package cn.buildoncloud.labor.workermanapplet.business.modules.services.impl;

import cn.buildoncloud.labor.workermanapplet.business.modules.services.WorkerTeamAttendanceService;
import cn.buildoncloud.labor.workermanapplet.common.base.service.BaseServiceImpl;
import cn.buildoncloud.labor.workermanapplet.common.page.Pagination;
import cn.buildoncloud.labor.workermanapplet.util.DateUtil;
import cn.buildoncloud.labor.workermanapplet.util.StringUtil;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Description: cn.buildoncloud.labor.workermanapplet.business.modules.services.impl
 * Created by CuiZibo on 2018/12/3 17:09
 */
@Service
public class WorkerTeamAttendanceServiceImpl extends BaseServiceImpl<Map> implements WorkerTeamAttendanceService {

    @Autowired
    private Dao dao;

    public WorkerTeamAttendanceServiceImpl(Dao dao) {
        super(dao);
    }

    /**
     *@create 2019/1/17 10:31
     *@Param [projectId, date, key, pageNumber, pageSize]
     *@return java.util.List<java.util.Map>
     *@desc 班组考勤  今日 - 新增分页
     */
    @Override
    public Pagination queryWorkerTeamAttendanceList(String projectId, String date, String key, Integer pageNumber, Integer pageSize) {
        boolean b = this.tableIsExist("bi_attendance_record_", StringUtil.last2num(projectId.toString()));
        if (!b) {
            return new Pagination();
        }
        StringBuffer sb = new StringBuffer();
        sb.append("SELECT CONCAT(t1.worker_team_id, '') tId, IFNULL(t2.count_, 0) _count,t4.`name` tName,t4.team_leader_name tlName,t4.team_leader_tel tlTel,GROUP_CONCAT(DISTINCT CONCAT(t5.`name`, '-', t6.`name`) SEPARATOR ',') workClasses,COUNT(DISTINCT t7.worker_man_id) count_ FROM bi_re_workerteam_project t1 ")
                .append("LEFT JOIN ( SELECT t1.team_id, COUNT(t1.id) count_ FROM `bi_attendance_record_$pid` t1 WHERE t1.project_id = @projectId AND t1.record_dt = @dt GROUP BY t1.team_id ) t2 ON t1.worker_team_id = t2.team_id ")
                .append("LEFT JOIN bi_re_workerteam_project_entend t3 ON t1.id = t3.reWorker_team_and_projectid LEFT JOIN bi_workerteam t4 ON t1.worker_team_id = t4.id ")
                .append("LEFT JOIN sys_work_class t5 ON t5.id = t3.work_class_id LEFT JOIN sys_work_type t6 ON t6.id = t3.work_type_id ")
                .append("LEFT JOIN bi_re_workman_and_teamproject t7 ON t7.reWorker_team_and_projectid = t1.id AND t7.workman_out_date IS NULL ")
                .append("where t1.project_id = @projectId AND t1.out_date is NULL ");
        if (StringUtil.isNotBlank(key)) {
            sb.append("AND t1.worker_team_id IN ( SELECT t.id FROM `bi_workerteam` t WHERE t. NAME LIKE @key OR t.team_leader_name LIKE @key OR t.team_leader_tel LIKE @key ) ");
        }
        sb.append("GROUP BY t1.id ORDER BY t2.count_ DESC ");
        Sql sql = Sqls.create(sb.toString());
        if (StringUtil.isNotBlank(key)) {
            sql.setParam("key", "%" + key + "%");
        }
        sql.setVar("pid", StringUtil.last2num(projectId))
                .setParam("dt", date)
                .setParam("projectId", projectId);
//                .setCallback((conn, rs, sql1) -> {
//                    List<Map> list = new ArrayList<>();
//                    while (rs.next()) {
//                        Map map = new HashMap();
//                        map.put("teamId", rs.getString("tId"));
//                        map.put("teamName", rs.getString("tName"));
//                        map.put("teamLeaderName", rs.getString("tlName"));
//                        map.put("teamLeaderTel", rs.getString("tlTel"));
//                        map.put("workClasses", rs.getString("workClasses"));
//                        map.put("inCount", rs.getInt("_count"));
//                        map.put("allCount", rs.getInt("count_"));
//                        list.add(map);
//                    }
//                    return list;
//                });
//        dao.execute(sql);
//        List<Map> list = sql.getList(Map.class);
        Pagination pagination = this.listPage(pageNumber, pageSize, sql);
        return pagination;
    }

    @Override
    public List<Map> queryWorkerTeamAttendanceByMonth(String projectId, String workerTeamId, String yearAndMonth) {
        List<Map> data = new ArrayList<>();
        //把年月日拆分
        String[] yymm = yearAndMonth.split("-");
        String year = yymm[0];
        String month = yymm[1];
        int days = DateUtil.getDaysByYearMonth(Integer.parseInt(year), Integer.parseInt(month));
        String begin = year + "-" + month + "-01";
        String end = year + "-" + month + "-" + days;
        boolean b = this.tableIsExist("bi_attendance_record_", StringUtil.last2num(projectId));
        if (b) {
            Sql sql = Sqls.create("SELECT CONCAT(t1.record_dt,'') date FROM `bi_attendance_record_$pid` t1 WHERE t1.team_id = @teamId and t1.project_id = @projectId AND t1.record_dt BETWEEN @begin AND @end GROUP BY t1.record_dt ");
            sql.setVar("pid", StringUtil.last2num(projectId))
                    .setParam("teamId", workerTeamId)
                    .setParam("projectId", projectId)
                    .setParam("begin", begin)
                    .setParam("end", end)
                    .setCallback((conn, rs, sql1) -> {
                        List<Map> list = new ArrayList<>();
                        while (rs.next()) {
                            Map map = new HashMap();
                            map.put("date", rs.getString("date"));
                            list.add(map);
                        }
                        return list;
                    });
            dao.execute(sql);
            data = sql.getList(Map.class);

        }
        return data;
    }

    @Override
    public Pagination queryWorkerTeamMembersAttendance(String projectId, String workerTeamId, String yymmdd, int pageNo, int pageSize) {
        boolean b = this.tableIsExist("bi_attendance_record_", StringUtil.last2num(projectId.toString()));
        if (!b) {
            return new Pagination();
        }
        StringBuffer sb = new StringBuffer();
        sb.append("SELECT t3.`name` manName, CONCAT(t3.id,'') manId, t3.sex, TIMESTAMPDIFF(YEAR, SUBSTRING(t3.id_card_no,7,8), CURDATE()) age, t3.tel, CONCAT(t3.head_photo_id,'') head_photo_id, CONCAT(t4.`name`,'-',t5.`name`) className, CASE t1.record_dt WHEN DATE(NOW()) THEN '未结算' ELSE CONCAT(t1.working_hours, '小时') END working_hours, t1.is_statistics_completed FROM `bi_attendance_record_$pid` t1 ")
                .append("LEFT JOIN bi_re_workman_and_teamproject t2 ON t2.worker_man_id = t1.worker_id LEFT JOIN bi_workerman t3 ON t3.id = t2.worker_man_id LEFT JOIN sys_work_class t4 ON t4.id = t2.work_class_id LEFT JOIN sys_work_type t5 ON t5.id = t2.work_type_id WHERE t1.project_id = @projectId AND t1.team_id = @teamId AND t1.record_dt = @dt GROUP BY t2.worker_man_id ORDER BY t1.working_hours desc ");
        Sql sql = Sqls.create(sb.toString());
        sql.setVar("pid", StringUtil.last2num(projectId))
                .setParam("dt", yymmdd)
                .setParam("projectId", projectId)
                .setParam("teamId", workerTeamId);
        return this.listPage(pageNo, pageSize, sql);
    }
}
